<template>
  <div class="departments-container">
    <div class="app-container">
      <!-- //! 卡片区域 -->
      <el-card v-loading="loading" class="tree-card">
        <!-- 用了一个行列布局 -->
        <el-row
          type="flex"
          justify="space-between"
          align="middle"
          style="height: 40px"
        >
          <el-col :span="20">
            <span>{{ companyName }}</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex">
              <!-- 两个内容 -->
              <el-col :span="12">负责人</el-col>
              <el-col :span="12">
                <!-- 下拉菜单 element -->
                <el-dropdown>
                  <span> 操作<i class="el-icon-arrow-down" /> </span>
                  <!-- 下拉菜单 -->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="openDialog(oneDepartmentInfo)">添加子部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <!-- //! el-tree组件 内容区域-->
        <el-tree :data="departs" :props="defaultProps">
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex">
                  <!-- 两个内容 -->
                  <el-col :span="12">{{ data.manager }}</el-col>
                  <el-col :span="12">
                    <!-- 下拉菜单 element -->
                    <!--  @command 可以触发事件 -->
                    <el-dropdown @command="handleCommand">
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <!-- 下拉菜单 -->
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item
                          :command="{ type: 'add', data }"
                        >添加子部门</el-dropdown-item>
                        <el-dropdown-item
                          :command="{ type: 'edit', data }"
                        >编辑子部门</el-dropdown-item>
                        <el-dropdown-item
                          :command="{ type: 'del', id: data.id }"
                        >删除子部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- //! dialog 弹框组件 -->
    <add-dept ref="addDept" :node-data="nodeData" :department-list="departmentList" />
  </div>
</template>

<script>
import addDept from './components/add-dept.vue'
import { getDepartmentListApi, delDepartmentApi } from '@/api/departments'
export default {
  name: 'Departments',
  components: {
    addDept
  },
  data() {
    return {
      // 加载条
      loading: false,
      // 所有部门数据
      departs: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 公司名称
      companyName: '',
      // 每一行的数据
      nodeData: {},
      // 全部的部门数据
      departmentList: [],
      // 拿到所有的一级部门，以及公司的id，已知一级部门pid === 公司id
      oneDepartmentInfo: {}
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    /**
     * 获取部门列表
     */
    async getDepartmentList() {
      this.loading = true
      const res = await getDepartmentListApi()
      this.departs = this.transListToTreeData(res.data.depts, '')
      this.companyName = res.data.companyName
      this.departmentList = res.data.depts
      // 给一级部门信息中赋值一个id为空
      this.oneDepartmentInfo.id = ''
      this.oneDepartmentInfo.children = this.departs
      this.loading = false
    },
    /**
     * !使用递归方法，将扁平数据改变成树状数据
     */
    transListToTreeData(list, searchVal) {
      // list 接收的是数据， searchVal 接收的表示一级的id
      const arr = []
      // 遍历查找一级
      list.forEach((item) => {
        if (item.pid === searchVal) {
          // 调用transListToTreeData函数查找2级
          const children = this.transListToTreeData(list, item.id)
          item.children = children
          // push 一级
          arr.push(item)
        }
      })
      return arr
    },
    /**
     * 将平铺数据转成树状结构数据
     */
    // transListToTreeData(list) {
    //   // 找到所有的一级
    //   let arr = []
    //   arr = list.filter(item => item.pid === '')

    //   // 找一级下所有的二级
    //   arr.forEach(element => {
    //     // 遍历list 找二级pid等于一级的id
    //     const children = list.filter(item => item.pid === element.id)
    //     // 找到一级下的二级，往一级中添加一个children属性
    //     element.children = children
    //   })
    //   return arr
    // }

    /**
     * ! 添加、编辑、删除逻辑
     */
    handleCommand({ type, id, data }) {
      if (type === 'add') {
        // 通过$refs找到当前组件示例，可以访问里面的方法和数据
        this.$refs.addDept.showDialog = true
        this.nodeData = data
        this.$refs.addDept.getEmployeeSimple()
      }
      if (type === 'edit') {
        // 调用打开编辑方法
        this.editDialog(data)
        this.$refs.addDept.getEmployeeSimple()
      }
      if (type === 'del') {
        this.delDepartment(id)
      }
    },
    /**
     *  发送删除请求
    */
    delDepartment(id) {
      this.$confirm('删不删除？', '提示')
        .then(async() => {
          await delDepartmentApi(id)
          this.$message.success('删除成功')
          this.getDepartmentList()
        })
        .catch(() => {})
    },
    // 点击公司 添加按钮 逻辑
    openDialog(data) {
      this.$refs.addDept.showDialog = true
      // 需要检验添加的一级部门名称不能重复
      this.nodeData = data
      console.log(this.nodeData)
    },
    /**
     * 点击编辑弹出弹框
     */
    editDialog(data) {
      this.$refs.addDept.showDialog = true
      this.nodeData = data
      // 需要等待所有的dom加载完成后调用
      this.$nextTick(() => {
        this.$refs.addDept.getDepartmentDetaile()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tree-card {
  padding: 30px 30px;
  font-size: 14px;
}

.el-tree {
  ::v-deep {
    // 小三角的样式, 去掉默认的小三角的旋转效果
    .el-tree-node__expand-icon.expanded {
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    // 有子节点 且未展开 +
    .el-icon-caret-right:before {
      background: url("~@/assets/common/add-circle.png") no-repeat 0 0;
      content: "";
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
    // 有子节点 且已展开 -
    .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
      background: url("~@/assets/common/minus-circle.png") no-repeat 0 0;
      content: "";
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
    // 没有子节点
    .el-tree-node__expand-icon.is-leaf::before {
      background: url("~@/assets/common/user-filling.png") no-repeat 0 0;
      content: "";
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
  }
}
</style>
